using System.Data.Objects;
using System.Data.Objects.DataClasses;
using Common.Core;

namespace Common.Unity.Extensions.Entity.Extensions
{
	public static class ObjectContextExtensions
	{
		public static void DeleteObjectEnsured( this ObjectContext target, object entity )
		{
			// HACK: Ensure all ends are loaded:
			foreach ( var info in entity.GetType().GetProperties( CommonBindingFlags.AllProperties ) )
			{
				if ( typeof(IRelatedEnd).IsAssignableFrom( info.PropertyType ) )
				{
					var end = info.GetValue( entity, null ) as IRelatedEnd;
					if ( end != null && !end.IsLoaded )
					{
						end.Load();
					}
				}
			}
			target.DeleteObject( entity );
		}
	}
}